package com.enjoy.adv.kryocodec;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufInputStream;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * Created by HP on 2019/7/18.
 */
public class KryoSerializer {
    private static Kryo kryo=KryoFactory.createKryo();

    /**
     * 序列化方法
     * @param object 需要系列化的对象
     * @param out 输出
     */
    public static void serialize(Object object, ByteBuf out){
        ByteArrayOutputStream baos=new ByteArrayOutputStream();
        Output output=new Output(baos);
        //写
        kryo.writeClassAndObject(output,object);
        output.flush();
        output.close();

        byte[] b=baos.toByteArray();


        try {
            baos.flush();
            baos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        out.writeBytes(b);
    }

    /**
     * 反序列化
     * @param out
     * @return
     */
    public static Object deSerialize(ByteBuf out){
        if (out==null){
            return null;
        }
        Input input=new Input(new ByteBufInputStream(out));
        //读
        return  kryo.readClassAndObject(input);
    }

}
